package com.yy.studyspringboot.concurrent;

import java.util.concurrent.*;

public class PhaserTest {
    /**  Phaser ---同步器
        案例点餐： 一个客户 一个客户的接待
     */

    public static void main(String[] args) throws InterruptedException {
        Phaser phaser = new Phaser(1);
        System.out.println("starting ..."   );

        new Worker(phaser,"服务员").start();
        new Worker(phaser,"厨师").start();
        new Worker(phaser,"传菜员").start();

        for (int i = 0; i <= 3; i++) {
            phaser.arriveAndAwaitAdvance();
            System.out.println("order " + i + "finished!");
        }
        phaser.arriveAndDeregister();
        System.out.println("All done!");
    }


}


class Worker extends Thread{
    private Phaser phaser;
    public Worker(Phaser phaser,String name){
        this.setName(name);
        this.phaser = phaser;
        //将自己注册到phaser中
        phaser.register();
    }

    @Override
    public void run() {
        for (int i = 0; i <= 3; i++) {
            System.out.println("current order is : " + i + " : " + getName());
            if (i == 3){
                //处理完：到达并注销
                phaser.arriveAndDeregister();
            }else {
                //未处理完：到达并等待前进
                phaser.arriveAndAwaitAdvance();
            }
            try {
                Thread.sleep(1000);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}